package com.gaxy.subject.application.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 * 当两个微服务之间做互相调用的时候，想拼各种各样的东西或者额外的传递，调用方都可以在这里做。
 *
 * @author Gaxy
 * @create 2024/06/22/下午 02:56
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //HttpServletRequest对象代表了客户端的HTTP请求
        HttpServletRequest request = requestAttributes.getRequest();
        if (Objects.nonNull(request)){
            String loginId = request.getHeader("loginId");
            if(StringUtils.isNotBlank(loginId)) {
                //RequestTemplate通常是Feign客户端用于构建HTTP请求的模板
                requestTemplate.header("loginId", loginId);
            }
        }
    }
}
